<template>
	<view class="wrap">
		<u-form class="form" :model="model" :rules="rules" ref="uForm" label-position="left">
			<view>
				<u-form-item label="任务年度" label-width="180">
					<js-select
						v-model="model.taskYear"
						:items="this.years"
						itemLabel="name"
						itemValue="value"
						:label-value="model.taskYear"
						@label-input="model.taskYear = $event"
						placeholder="请选择任务年度"
					></js-select>
				</u-form-item>
				<view class="pp">
					<span style="color: red">*</span>
					<u-form-item label="任务类型" prop="taskTypeCode" class="re" label-width="180">
						<js-select v-model="model.taskTypeCode" dict-type="dc_task_type" @confirm="TypeCode(arguments)" placeholder="请选择任务类型"></js-select>
					</u-form-item>
				</view>
				<view class="pp">
					<span style="color: red">*</span>
					<u-form-item label="任务标题" prop="taskTitle" label-width="180">
						<u-input placeholder="请输入任务标题" v-model="model.taskTitle" type="textarea" maxlength="200"></u-input>
					</u-form-item>
				</view>
				<view class="pp active">
					<span class="pp_span" style="color: red">*</span>
					<u-form-item label="任务内容" prop="taskContent" label-width="180" label-position="top">
						<u-input type="textarea" placeholder="请输入任务内容" v-model="model.taskContent" height="100" maxlength="500" />
					</u-form-item>
				</view>

				<view class="pp">
					<span style="color: red">*</span>
					<u-form-item label="开始时间" prop="taskStartTime" label-width="180">
						<uni-datetime-picker
							type="datetime"
							v-model="model.taskStartTime"
							:border="false"
							@change="startTime"
							placeholder="请输入开始时间"
							:clearIcon="false"
							ref="infomation"
							@click="kk"
						/>
					</u-form-item>
				</view>
				<view class="pp">
					<span style="color: red">*</span>
					<u-form-item label="结束时间" prop="taskEndTime" label-width="180">
						<uni-datetime-picker type="datetime" v-model="model.taskEndTime" :border="false" :clearIcon="false" placeholder="请输入结束时间" />
					</u-form-item>
				</view>
				<u-form-item label="牵头领导" prop="taskLeader" label-width="180">
					<ld-select
						v-if="this.text1 == 2"
						:multiple="true"
						:list="this.userSelectList"
						label-key="label"
						value-Key="value"
						placeholder="请选择"
						clearable
						v-model="model.taskLeader"
						@change="selectChange2"
						style="width: 90%; text-align: left; margin: auto; font-size: 14px"
					></ld-select>

					<u-input placeholder="" v-if="this.text1 == 1" v-model="text11" type="textarea" width="180px" height="150px"></u-input>
				</u-form-item>

				<view class="pp">
					<span style="color: red">*</span>
					<u-form-item label="牵头责任单位" prop="taskLeaderOrg" label-width="180" v-if="model.taskLeaderOrg == ''">
						<button
							@tap="showTree"
							type="default"
							style="
                width: 90%;
                text-align: left;
                margin: auto;
                height: 80rpx;
                border: 1px solid #f4f4f4;
                font-size: 14px;
              "
						>
							请选择
						</button>
					</u-form-item>
					<u-form-item label="牵头责任单位" label-width="180" v-if="model.taskLeaderOrg != ''">
						<u-input placeholder="" disabled v-model="text" @click="showTree()" type="textarea" width="180px" height="150px"></u-input>
					</u-form-item>
				</view>

				<view class="pp">
					<span style="color: red">*</span>
					<u-form-item label="联系人" prop="contactName" label-width="180">
						<u-input placeholder="请输入联系人" v-model="model.contactName" type="text" maxlength="200"></u-input>
					</u-form-item>
				</view>
				<view class="pp">
					<span style="color: red">*</span>
					<u-form-item label="联系电话" prop="contactPhone" label-width="180">
						<u-input placeholder="请输入联系电话" v-model="model.contactPhone" type="text" maxlength="200"></u-input>
					</u-form-item>
				</view>
				<view class="pp">
					<span style="color: red">*</span>
					<u-form-item label="督办字号" prop="msgNum2" label-width="180">
						<js-select v-model="model.msgNum" dict-type="dc_num_common" @label-value="Num"></js-select>
						<u-input v-model="model.msgNum2" type="text" maxlength="200" placeholder="请输入督办字号"></u-input>
					</u-form-item>
				</view>
				<u-form-item label="生成督办单" prop="formFlag" label-width="180"><js-radio v-model="model.formFlag" dict-type="sys_yes_no"></js-radio></u-form-item>

				<u-form-item label="审核人" prop="auditorCode" label-width="180">
					<js-select
						v-model="model.auditorCodeStr"
						:items="userSelectList1"
						placeholder="请选择人员"
						:tree="true"
						@confirm="LeaderOrg(arguments)"
						:label-value="model.auditorName"
						@label-input="model.auditorCode = $event"
					></js-select>
					<span class="input-group-addon" v-if="model.auditorName != ''" @click="clickX">X</span>
					<view :class="this.num123 == 2 ? '' : 'shadow2'"></view>
				</u-form-item>
			</view>
			<!-- 附件 -->
			<view class="lh-mt-36 ipbox"><LhFilelist v-if="model.id" :bizKey="model.id" impor bizType="dcSupTaskInfo_file" /></view>
		</u-form>
		<view class="form-footer"><u-button class="btn" type="primary" @click="submit" v-if="taskStatus == 4 || model.id == ''">提交</u-button></view>
		<view class="content">
			<tki-tree
				ref="tkitree"
				:selectParent="selectParent"
				:multiple="multiple"
				:range="officeSelectList"
				:foldAll="flod"
				:defalutSelect="this.model.taskLeaderOrg"
				rangeKey="name"
				@confirm="treeConfirm"
				@cancel="treeCancel"
			></tki-tree>
		</view>

		<view class="shadow1" v-if="this.num == 2"></view>
	</view>
</template>
<script>
/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
import tkiTree from '@/components/tki-tree/tki-tree.vue';
import LhFilelist from '@/components/lh-filelist/lh-filelist.vue';
export default {
	components: {
		tkiTree,
		LhFilelist
	},
	data() {
		return {
			dictList: [],
			value: '',
			k: 'k',
			text1: '',
			text11: '',
			text: '',
			num123: 1,
			title: '审核意见',
			label: '',
			multiple: true,
			selectParent: true,
			flod: true,
			taskStatus: 0,
			years: [], // 任务年度初始备选值
			model: {
				id: '',
				taskYear: new Date().getFullYear(),
				taskTypeCode: '',
				taskTypeName: '',
				taskTitle: '',
				taskContent: '',

				targetType: '',
				targetId: '',
				taskId: '',
				auditorCode: '',
				feedbackWay: 4,
				auditorName: '',
				taskStatus: '2',
				contactName: '',
				contactPhone: '',
				formFlag: '0',
				auditFlag: '0',
				attachmentFlag: '0',
				taskStartTime: '',
				taskEndTime: '',
				taskLeader: [],
				taskLeaderName: [],
				taskLeaderOrg: [],
				taskLeaderOrgName: [],
				msgNum: '督一〔2022〕',
				msgNum2: '',
				messageNumber: '',
				remarks2: 'app',
				normalFlag: 1,
				dcSupTaskInfo_file: '',
				dcSupTaskInfo_file__del: ''
			},
			rules: {
				taskStartTime: [
					{
						required: true,
						message: '请选择开始时间'
					}
				],
				taskEndTime: [
					{
						required: true,
						message: '请选择时间'
					}
				],
				msgNum2: [
					{
						required: true,
						message: '请选择督办字号'
					}
				],
				taskTypeCode: [
					{
						required: true,
						message: '请选择任务类型',
						trigger: ['change', 'blur']
					}
				],
				taskTitle: [
					{
						required: true,
						message: '请输入任务标题',
						trigger: ['change', 'blur']
					}
				],
				taskContent: [
					{
						required: true,
						message: '请输入任务内容',
						trigger: ['change', 'blur']
					}
				],
				taskLeaderOrg: [
					{
						required: true,
						message: '请选择牵头责任单位',
						trigger: ['change', 'blur']
					}
				],
				contactPhone: [
					{
						pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/,
						message: '请输入正确的手机号码',
						trigger: ['change', 'blur']
					},
					{
						required: true,
						message: '请输入联系电话',
						trigger: ['change', 'blur']
					}
				],
				testInput: [
					{
						required: true,
						message: '请输入单行文本',
						trigger: ['change', 'blur']
					}
				]
			},
			officeSelectList: [],
			userSelectList1: [],
			userSelectList: []
		};
	},
	created() {
		// console.log(this.num123);
		setTimeout(() => {
			this.num123 = 2;
		}, 3000);
		// console.log(this.num123);
		this.num = uni.getStorageSync('add');
	},
	watch: {
		num123(val, oldval) {
			// console.log(val);
			this.num123 = val;
		}
	},
	onLoad(params) {
		if (params.id == undefined) {
			this.$u.api.taskInfo.msgNum2().then(res => {
				this.model.msgNum2 = res;
				this.model.messageNumber = this.model.msgNum + this.model.msgNum2;
			});
			// 新增时，初始化任务开始时间
			this.model.taskStartTime = this.getStartTime();
		}
		this.model.contactName = this.vuex_user.userName;
		this.model.contactPhone = this.vuex_user.mobile;
		// console.log(location.href.indexOf("id"), "location.href.indexOf");
		if (location.href.indexOf('id') != -1) {
			this.text1 = 1;
			uni.setNavigationBarTitle({
				title: '任务详情'
			});
		} else {
			this.text1 = 2;
			uni.setNavigationBarTitle({
				title: '任务新增'
			});
		}

		if (params.id != undefined) {
			this.$u.api.taskInfo.list({ id: params.id, dataLimit: 0 }).then(res => {
				// this.officeSelectList = res;
				console.log(res.list.length, res.list[0].taskLeaderName, '123123123123123123312');

				if (res.list && res.list.length > 0) {
					let that = this;
					// 回显
					that.model.id = res.list[0].id;
					that.model.taskYear = res.list[0].taskYear;
					that.model.taskTypeCode = res.list[0].taskTypeCode;
					that.model.taskTypeName = res.list[0].taskTypeName;
					that.model.taskLeaderName = res.list[0].taskLeaderName;
					that.model.taskLeaderOrgName = res.list[0].taskLeaderOrgName;
					that.model.taskTitle = res.list[0].taskTitle;
					that.model.taskContent = res.list[0].taskContent;
					that.model.taskStartTime = res.list[0].taskStartTime;
					that.model.taskEndTime = res.list[0].taskEndTime;
					that.model.contactName = res.list[0].contactName;
					that.model.contactPhone = res.list[0].contactPhone;
					that.model.msgNum = res.list[0].msgNum;
					that.model.msgNum2 = res.list[0].msgNum2;
					that.model.formFlag = res.list[0].formFlag;
					that.model.auditFlag = res.list[0].auditFlag;
					that.model.auditStatus = res.list[0].auditStatus;
					that.model.auditorCode = res.list[0].auditorCode;
					that.model.auditorName = res.list[0].auditorName;
					that.model.auditType = res.list[0].auditType;
					that.model.createBy = res.list[0].createBy;
					that.taskStatus = res.list[0].taskStatus;
					if (res.list[0].taskLeader && res.list[0].taskLeader.length > 0) {
						setTimeout(function() {
							that.model.taskLeader = res.list[0].taskLeader.split(',');
						}, 3000);
					}

					that.text = res.list[0].taskLeaderOrgName;
					that.text11 = res.list[0].taskLeaderName;
					that.model.taskLeaderOrg = res.list[0].taskLeaderOrg;
				}
			});
		}
		// 获取任务年度备选值
		this.getYears();
	},
	onReady() {
		this.$refs.uForm.setRules(this.rules);
		// 机构数据

		// this.$u.api.getLoginOffice().then(res=>{
		//   this.$u.api.office.treeDataWithMobile({isLoadUser: true,parentCode:res.employeeOffice.parentCodes}).then(res => {
		//     this.userSelectList1 = res;
		//   });
		// })

		this.$u.api.getLoginOffice().then(res => {
			this.$u.api.office
				.treeData({
					isLoadUser: true,
					parentCode: res.employeeOffice.parentCodes
				})
				.then(res => {
					this.userSelectList1 = res;
				});
		});
		this.$u.api.office.treeUnitData().then(res => {
			let data = [];
			res.forEach(item => {
				if (item.isParent == true) {
					data.push(item);
				}
			});
			let i,
				l,
				key = 'id',
				parentKey = 'pId',
				childKey = 'children';
			if (Object.prototype.toString.apply(data) === '[object Array]') {
				let treeData = [],
					map = [];
				for (i = 0, l = data.length; i < l; i++) {
					map[data[i][key]] = data[i];
				}
				for (i = 0, l = data.length; i < l; i++) {
					if (map[data[i][parentKey]] && data[i][key] != data[i][parentKey]) {
						if (!map[data[i][parentKey]][childKey]) {
							map[data[i][parentKey]][childKey] = [];
						}
						map[data[i][parentKey]][childKey].push(data[i]);
					} else {
						treeData.push(data[i]);
					}
				}

				this.officeSelectList = treeData;
			} else {
			}
		});
		this.$u.api.taskInfo.getLeader().then(res => {
			res.data.map(item => {
				this.userSelectList.push({
					label: item.userName,
					value: item.userCode
				});
			});
			// console.log(this.userSelectList);
		});
	},
	methods: {
		// 获取任务年度备选值
		getYears() {
			let yearNumber = 5;
			let yearList = [];
			let currentYear = new Date().getFullYear();
			for (let j = yearNumber; j >= 1; j--) {
				yearList.push({ name: currentYear + j, value: currentYear + j });
			}
			for (let i = 0; i <= yearNumber; i++) {
				yearList.push({ name: currentYear, value: currentYear });
				currentYear -= 1;
			}
			this.years = yearList;
		},
		// 获取默认的开始时间
		getStartTime() {
			let now = new Date();
			let year = now.getFullYear(); //得到年份
			let month = now.getMonth(); //得到月份
			let day = now.getDate(); //得到天
			if (day < 10) {
				day = '0' + day;
			}
			month = month + 1;
			month = month.toString().padStart(2, '0');
			return year + '-' + month + '-' + day + ' 00:00:00';
		},
		startTime() {},
		// 确定回调事件
		clickX() {
			this.model.auditorCode = '';
			this.model.auditorCodeStr = '';
			this.model.auditorName = '';
		},

		blur() {
			this.model.taskLeaderOrg = [];
		},
		clear() {},
		treeConfirm(e) {
			console.log(e);
			this.model.taskLeaderOrgName = [];
			this.model.taskLeaderOrg = [];
			e.forEach(item => {
				this.model.taskLeaderOrgName.push(item.name);
				this.model.taskLeaderOrg.push(item.id);
			});
			this.text = this.model.taskLeaderOrgName.join(',');
		},
		// 取消回调事件
		treeCancel(e) {},
		// 显示树形选择器
		showTree() {
			this.$refs.tkitree._show();
		},

		cancel() {},
		confirm() {},

		year(val) {
			this.model.taskYear = val;
		},
		TypeCode(val) {
			this.model.taskTypeCode = val[0];
			this.model.taskTypeName = val[1];
		},
		LeaderOrg(val) {
			console.log(val);
			if (val[0] == '' || val[1] == '') {
				uni.showModal({
					title: '提示',
					content: '该机构没有负责人，请忽略或者选择其他机构下的人员',
					showCancel: true
					// success: function() {
					// 	if (res.result == 'true') {
					// 		uni.setStorageSync('refreshList', true);
					// 		// uni.navigateTo({
					// 		// 	url: './taskInfoList'
					// 		// });
					// 		uni.navigateBack();
					// 	}
					// }
				});
			}
			this.model.auditorCode = val[0];
			this.model.auditorName = val[1];
		},
		selectChange2(val) {
			const newArray = [];
			val.forEach(item => {
				newArray.push({
					value: item
				});
			});

			this.model.taskLeader = val;
			const newArray1 = [];
			if (newArray && newArray.length > 0) {
				newArray.forEach((item, index) => {
					this.userSelectList.forEach((item1, index1) => {
						if (item.value == item1.value) {
							newArray1.push(item1.label);
						}
					});
				});
				this.model.taskLeaderName = newArray1.join(',');
			}
		},
		Num(val) {
			this.model.msgNum = val;
		},

		submit() {
			this.model.messageNumber = this.model.msgNum + this.model.msgNum2;
			if (this.model.dataMap) {
				this.model.dcSupTaskInfo_file = this.model.dataMap.dcSupTaskInfo_file;
				this.model.dcSupTaskInfo_file__del = this.model.dataMap.dcSupTaskInfo_file__del;
			}
			delete this.model.dataMap;
			this.$refs.uForm.validate(valid => {
				if (valid) {
					this.$u.api.taskInfo.save(this.model).then(res => {
						uni.showModal({
							title: '提示',
							content: res.message,
							showCancel: false,
							success: function() {
								if (res.result == 'true') {
									uni.setStorageSync('refreshList', true);
									// uni.navigateTo({
									// 	url: './taskInfoList'
									// });
									uni.navigateBack();
								}
							}
						});
					});
				} else {
					this.$u.toast('您填写的信息有误，请根据提示修正。');
				}
			});
		}
	}
};
</script>
<style lang="scss">
.u-model__title {
	color: #ff0000 !important;
}
.ipbox {
	z-index: 999;
}
.shadow1 {
	position: fixed;
	top: 5%;
	width: 100%;
	height: 100%;
	z-index: 998;
	background-color: rgba(255, 255, 255, 0.1);
}
.shadow2 {
	position: fixed;
	top: 80%;
	width: 100%;
	height: 10%;
	z-index: 998;
	background-color: rgba(255, 255, 255, 0.1);
}
.pp {
	display: flex;
	justify-content: left;
	align-items: center;
	&.active {
		align-items: flex-start;

		.pp_span {
			padding: 20rpx 0 0 0;
			line-height: 70rpx;
		}
	}
}
.u-form-item {
	flex: 1;
}
</style>
